#!/usr/bin/python
# -*- coding: UTF-8 -*-

from common.readconfig import ReadConfig
import pymysql.cursors

class HandleMysql:
    def __init__(self,section):
        self.data = ReadConfig()
        self.name = section

    def conn_mysql(self):
        """连接数据库"""
        host = self.data.get_sec_db(self.name,"host")
        user = self.data.get_sec_db(self.name,"user")
        password = self.data.get_sec_db(self.name,"password")
        db = self.data.get_sec_db(self.name,"database")
        charset = self.data.get_sec_db(self.name,"charset")
        self.conn = pymysql.connect(host=host, user=user, password=password, db=db, charset=charset,cursorclass=pymysql.cursors.DictCursor)
        self.cur = self.conn.cursor()

    def execute_sql(self, sql, data):
        """执行操作数据的相关sql"""
        self.conn_mysql()
        self.cur.execute(sql, data)
        self.conn.commit()
    
    def execute_many(self, sql, datas):
        """执行操作数据的相关sql"""
        self.conn_mysql()
        self.cur.executemany(sql, datas)
        self.conn.commit()
    
    def query_cursor(self, sql):
        """执行查询sql"""
        self.conn_mysql()
        self.cur.execute(sql)
        return self.cur

    def search(self, sql):
        """执行查询sql"""
        self.conn_mysql()
        self.cur.execute(sql)
        return self.cur.fetchall()

    def close_mysql(self):
        """关闭数据库连接"""
        if not(self.cur is None):
            self.cur.close()
        if self.conn:
            self.conn.close()


if __name__ == '__main__':
    test = HandleMysql("source-database")
    sql = "select * from ecs_ad"
    for i in test.search(sql):
        print(i)